function [gg] = avg_inf_1to5(A,bt,pi_bar,pi_lim)

g = A(bt,:)';
pi = pi_bar;
s = size(pi_bar,1);
bin = (1:s)';
tol = 1e-7;
for i = 2:5
    pi = pi*(i-1)/i + pi_bar'/i;
    g = g.*A(bin,:);
    bin = repmat((1:s),size(g,1),1);
    pi = pi(:); bin = bin(:); g = g(:);
    d = [pi bin];
    [d,~,ic] = uniquetol(d,tol,'ByRows',true);
    dr = size(d,1);
    d = [d -ones(dr,1)]; %#ok<AGROW>
%    d(:,3) = sum(repmat(g',dr,1).*(repmat(ic',dr,1)==repmat((1:dr)',1,size(g,1))),2); % loop below = this line, loop is faster
    for j = 1:dr
        d(j,3) = sum(g(ic==j,1));
    end
    d(d(:,3)==0,:) = [];
    pi = d(:,1); bin = d(:,2); g = d(:,3);
end

bin = (pi_lim'-pi>-tol); bin  = s+1 - sum(bin,2);
gg = zeros(s,1);
for i = 1:s
    gg(i,1) = sum(g(bin==i,1));
end
